package com.example.alpha.campusbase.Activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.alpha.campusbase.R;
import com.example.alpha.campusbase.User;
import com.example.alpha.campusbase.UserLocalStore;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.rengwuxian.materialedittext.MaterialAutoCompleteTextView;

/**
 * Created by Alpha on 2016/6/3.
 */
public class RegisterActivity extends AppCompatActivity{

    // UI references.
    private MaterialAutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private MaterialEditText mNameView;
    private MaterialEditText mCampusView;
    private View mProgressView;
    private View mRegisterFormView;
    private UserLocalStore userLocalStore;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mContext=this;

        mEmailView = (MaterialAutoCompleteTextView) findViewById(R.id.re_email);
        mPasswordView = (EditText) findViewById(R.id.re_password);
        mCampusView= (MaterialEditText) findViewById(R.id.re_campus);
        mNameView= (MaterialEditText) findViewById(R.id.re_userName);

        Button mRegisterButton= (Button) findViewById(R.id.register_button);
        if (mRegisterButton != null) {
            mRegisterButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    verifyRegist();
                }
            });
        }

        mRegisterFormView = findViewById(R.id.register_form);
        mProgressView = findViewById(R.id.register_progress);

        userLocalStore=new UserLocalStore(this);
    }


    /**
     * 注册信息校验
     */
    private void verifyRegist() {

        // Reset errors.设置无错
        mEmailView.setError(null);
        mPasswordView.setError(null);
        mNameView.setError(null);
        mCampusView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();
        String campusname=mCampusView.getText().toString();
        String name=mNameView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            User user=new User(email,password,campusname
                    ,name.length()>0?name:email.substring(0,email.indexOf("@")));
            userLocalStore.storeUserData(user);
            userLocalStore.setUserLoggenIn(true);

            registerSucceed();
        }
    }

    //验证邮箱
    private boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        return email.contains("@");
    }

    //验证密码
    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mRegisterFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mRegisterFormView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mRegisterFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mRegisterFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    private void registerSucceed(){
        Intent intent=new Intent(mContext,MainActivity.class);
        startActivity(intent);
        finish();
    }


    //在登陆界面返回则退出APP
    @Override
    public void onBackPressed() {
        Intent homeIntent = new Intent(RegisterActivity.this,LoginActivity.class);
        startActivity(homeIntent);
        super.onBackPressed();
    }
}
